using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RotationUI
{
    /// <summary>
    /// 源
    /// </summary>
    public class Source
    {
        /// <summary>
        /// 生产动画帧
        /// </summary>
        public event Action<Bitmap> FrameRefresh;
        /// <summary>
        /// 动画运动线程
        /// </summary>
        private Task RunTask;
        /// <summary>
        /// 用来终止线程的
        /// </summary>
        CancellationTokenSource tokenSource;
        /// <summary>
        /// 原始图源
        /// </summary>
        public List<BitmapData> bitmapData;
        /// <summary>
        /// 台阶数量
        /// </summary>
        public int StepsNumber  { get; set; }
        /// <summary>
        /// 一轮运动次数
        /// </summary>
        public int RunCount { get; set; }
        /// <summary>
        /// 运动间隔 单位毫秒
        /// </summary>
        public int RunInterval { get; set; }
        /// <summary>
        /// 一轮运动时长
        /// </summary>
        public int RunTime { get; set; }
        public Source()
        {
            StepsNumber  = 2;
        }

        /// <summary>
        /// 添加图源
        /// </summary>
        /// <param name="path"></param>
        public void AddBitmapData(string path)
        {
            BitmapData data = new BitmapData();
            data.bitmap = new Bitmap(path);
            if (bitmapData == null)
            {
                bitmapData = new List<BitmapData>();
            }
            bitmapData.Add(data);
        }
        public virtual Bitmap GetBitmap()
        {
            return null;
        }
        public void Run()
        {
            if (RunTask != null && RunTask.Status != TaskStatus.Running)
            {
                Stop();
            }
            tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;
            RunTask = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                    FrameRefresh?.Invoke(GetBitmap());
                    Thread.Sleep(RunInterval);
                    //break;
                }
            });
        }

        public void Stop()
        {
            tokenSource.Cancel();
            RunTask.Wait();
            tokenSource.Dispose();
        }
    }
}
